package study.zhangxh.annotations.beans;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 说明
 *
 * @author: zhangxh
 * @email: zhangxh@cheegu.com
 * @date: 2018/6/25 22:56
 */
public class TableCreator {
    public  static  void  main(String[] args) throws Exception{
        if (args.length < 1) {
            System.out.println("arguments: annotated classes");
            System.exit(0);

        }
        for (String className : args) {
            Class<?> cl = Class.forName(className);
            DBTable dbTable = cl.getAnnotation(DBTable.class);
            if (dbTable == null) {
                System.out.println("No Table");
                continue;

            }
            String tableName=dbTable.name();
            if (tableName.length() < 1) {
                tableName = cl.getName().toUpperCase();

            }
            List<String> columnDefs=new ArrayList<>();
            for (Field field : cl.getDeclaredFields()) {
                String columenName=null;
                Annotation[] anns = field.getDeclaredAnnotations();
                if (anns.length < 1) {
                    continue;
                }
                if (anns[0] instanceof SQLInteger) {
                    SQLInteger sInt=(SQLInteger)anns[0];
                    if (sInt.name().length()<1)
                        columenName=field.getName().toUpperCase();
                    else
                        columenName=sInt.name();
                    columnDefs.add(columenName+" INT "+getConstrains(sInt.constraints()));
                }
                if (anns[0] instanceof SQLString) {
                    SQLString sString=(SQLString)anns[0];
                    if (sString.name().length()<1)
                        columenName=field.getName().toUpperCase();
                    else
                        columenName=sString.name();
                    columnDefs.add(columenName + " VARCHAR(" + sString.value() + ") " + getConstrains(sString.constraints()));
                }
                StringBuilder createCommand=new StringBuilder("CREATE TABLE "+tableName+"(");
                for (String columnDef : columnDefs) {
                    createCommand.append("\n    "+columnDef+",");
                }
                String tableCreate=createCommand.substring(0,createCommand.length()-1)+");";
                System.out.println("Table Creation SQL for "+className+" is :\n"+tableCreate);
            }
        }
    }

    private static String getConstrains(Constraints con) {
        String constraints = "";
        if (!con.allowNull())
            constraints+=" NOT NULL";
        if (con.primaryKey())
            constraints+=" PRIMARY KEY";
        if (con.unique())
            constraints+= " UNIQUE";
        return  constraints;
    }
}
